package com.sensePlusVR.widget.sliddel;

import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;

import com.sensePlusVR.adapter.CollectionListAdapter;
import com.sensePlusVR.adapter.CollectionListAdapter.ViewHolders;
import com.sensePlusVR.adapter.FollowDetailListAdapter;
import com.sensePlusVR.adapter.LocalVideoAdapter;
import com.sensePlusVR.adapter.LocalVideoAdapter.LocalVideoViewHolder;
import com.sensePlusVR.adapter.NetworkVideoAdapter;
import com.sensePlusVR.adapter.NetworkVideoAdapter.NetworkVideoViewHolder;
import com.sensePlusVR.adapter.NotifiSettingAdapter;
import com.sensePlusVR.utils.MyLog;

@SuppressWarnings("unused")
@SuppressLint({ "ClickableViewAccessibility", "HandlerLeak" })
public class ItemRemoveRecyclerView extends RecyclerView {
	private static final String TAG = ItemRemoveRecyclerView.class
			.getSimpleName();
	
	

	private Context mContext;

	// 上一次的触摸点
	private int mLastX, mLastY;
	// 当前触摸的item的位置
	private int mPosition;

	// item对应的布局
	private LinearLayout mItemLayout;
	
	//缩略图
	private FrameLayout mThumbnail;
	//标题
	private LinearLayout mTitle;
	
	private RelativeLayout collection_speed_relative;
	//赞按钮
	private LinearLayout mPraise;
	private LinearLayout mPlay;
	//下载按钮
	private LinearLayout mDownload;
	//置顶按钮
	private TextView mTop;
	// 删除按钮
	private TextView mDelete;

	// 最大滑动距离(即删除按钮的宽度)
	private int mMaxLength;
	// 是否在垂直滑动列表
	private boolean isDragging;
	// item是在否跟随手指移动
	private boolean isItemMoving;

	// item是否开始自动滑动
	private boolean isStartScroll;
	// 删除按钮状态 0：关闭 1：将要关闭 2：将要打开 3：打开
	private int mDeleteBtnState;
	
	public static final int BTN_CLOSED = 0;
	public static final int BTN_CLOSING = 1;
	public static final int BTN_OPENING = 2;
	public static final int BTN_OPENED = 3;

	// 检测手指在滑动过程中的速度
	private VelocityTracker mVelocityTracker;
	private Scroller mScroller;
	private OnItemClickListener mListener;
	

	public ItemRemoveRecyclerView(Context context) {
		this(context, null);
	}

	public ItemRemoveRecyclerView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ItemRemoveRecyclerView(Context context,
			 AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;

		mScroller = new Scroller(context, new LinearInterpolator());
		mVelocityTracker = VelocityTracker.obtain();
	}
	
	float downX = 0;
	float downY = 0;
	
	float moveX = 0;
	float moveY = 0;
	  
	@Override
	public boolean onInterceptTouchEvent(MotionEvent e) {
		if(mVelocityTracker != null){
			mVelocityTracker.addMovement(e);
		}
		MyLog.d(TAG, "onInterceptTouchEvent action : " + e.getAction());
		int x = (int) e.getX();
		int y = (int) e.getY();
		switch (e.getAction()) {
		case MotionEvent.ACTION_DOWN:
			   downX = x;
	           downY = y;
	           moveX = 0;  
	           moveY = 0;  
	           MyLog.d(TAG, "mDeleteBtnState : " + mDeleteBtnState);
	           
			if (mDeleteBtnState == BTN_CLOSED) {
				
				View view = findChildViewUnder(x, y);
				if (view == null)return false;
				ViewHolder viewHolderBase = getChildViewHolder(view);
				if (viewHolderBase instanceof NotifiSettingAdapter.NotifyViewHolder) {
					NotifiSettingAdapter.NotifyViewHolder viewHolder = (NotifiSettingAdapter.NotifyViewHolder) viewHolderBase;
					mItemLayout = viewHolder.layout;
					mPosition = viewHolder.getAdapterPosition();
				} else if (viewHolderBase instanceof LocalVideoAdapter.LocalVideoViewHolder) {
					LocalVideoAdapter.LocalVideoViewHolder viewHolder = (LocalVideoViewHolder) viewHolderBase;
					mItemLayout = viewHolder.layout;
					mPosition = viewHolder.getAdapterPosition();
				} else if (viewHolderBase instanceof NetworkVideoAdapter.NetworkVideoViewHolder) {
					NetworkVideoAdapter.NetworkVideoViewHolder viewHolder = (NetworkVideoViewHolder) viewHolderBase;
					mItemLayout = viewHolder.layout;
					mPosition = viewHolder.getAdapterPosition();
				} else if (viewHolderBase instanceof CollectionListAdapter.ViewHolders){
					CollectionListAdapter.ViewHolders viewHolder = (ViewHolders) viewHolderBase;
					mItemLayout = viewHolder.layout;
					mPosition = viewHolder.getAdapterPosition();
					//非共组件设置单机事件何时可用何时不可用
					mThumbnail = viewHolder.collection_fram;
					mTitle = viewHolder.collection_name_linear;
					collection_speed_relative = viewHolder.collection_speed_relative;
					mPraise = viewHolder.collection_zan_linear;
					mPlay = viewHolder.collection_play_linear;
					mDownload = viewHolder.collection_download_linear;
					mDelete = viewHolder.delete;
					mTop = viewHolder.top;
					
					mThumbnail.setClickable(true);
					mTitle.setClickable(true);
					collection_speed_relative.setClickable(true);
					mPraise.setClickable(true);
					mPlay.setClickable(true);
					mDownload.setClickable(true);
					
					if(mListener != null){
						mListener.onDeleteState(x,y);
					}
					
				}else if(viewHolderBase instanceof FollowDetailListAdapter.ViewHolders){
					FollowDetailListAdapter.ViewHolders viewHolder = (com.sensePlusVR.adapter.FollowDetailListAdapter.ViewHolders) viewHolderBase;
					mItemLayout = viewHolder.layout;
					mPosition = viewHolder.getAdapterPosition();
					
					mThumbnail = viewHolder.collection_fram;
					mTitle = viewHolder.collection_name_linear;
					collection_speed_relative = viewHolder.collection_speed_relative;
					mPraise = viewHolder.collection_zan_linear;
					mPlay = viewHolder.collection_play_linear;
					mDownload = viewHolder.collection_download_linear;
					mDelete = viewHolder.delete;
					mTop = viewHolder.top;
					
					
					mThumbnail.setClickable(true);
					mTitle.setClickable(true);
					collection_speed_relative.setClickable(true);
					mPraise.setClickable(true);
					mPlay.setClickable(true);
					mDownload.setClickable(true);
					
					if(mListener != null){
						mListener.onDeleteState(x,y);
					}
				}
				
				MyLog.d(TAG, "mPosition : " + mPosition);
				mMaxLength = mDelete.getWidth() + mTop.getWidth();
				mDelete.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(mListener == null)return;
						mListener.onDeleteClick(mPosition);
						//此处回调处理
					}
				});
				mTop.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(mListener == null)return;
						mListener.onTopClick(mPosition);
						startRecovery();
					}
				});
			} else if (mDeleteBtnState == BTN_OPENED || mDeleteBtnState == BTN_OPENING || mDeleteBtnState == BTN_CLOSING) {
				if(mThumbnail != null)
				mThumbnail.setClickable(false);
				if(mTitle != null)
				mTitle.setClickable(false);
				if(collection_speed_relative != null)
					collection_speed_relative.setClickable(false);
				if(mPraise != null)
				mPraise.setClickable(false);
				if(mPlay != null)
				mPlay.setClickable(false);
				if(mDownload != null)
				mDownload.setClickable(false);
				
				//删除和置顶要相应单机事件
				if(isTouchPointInView(mDelete, (int)e.getRawX(), (int)e.getRawY()) || isTouchPointInView(mTop, (int)e.getRawX(), (int)e.getRawY())){
					return false;
				}
					
				View viewCur = findChildViewUnder(x, y);
				if (viewCur == null)
					return false;

				ViewHolder viewHolderBase = getChildViewHolder(viewCur);

				if (viewHolderBase instanceof CollectionListAdapter.ViewHolders) {
					CollectionListAdapter.ViewHolders viewHolder = (ViewHolders) viewHolderBase;
					viewHolder.collection_fram.setClickable(false);
					viewHolder.collection_name_linear.setClickable(false);
					viewHolder.collection_speed_relative.setClickable(false);
					viewHolder.collection_zan_linear.setClickable(false);
					viewHolder.collection_play_linear.setClickable(false); 
					viewHolder.collection_download_linear.setClickable(false);

				}else if(viewHolderBase instanceof FollowDetailListAdapter.ViewHolders){
					FollowDetailListAdapter.ViewHolders viewHolder = (com.sensePlusVR.adapter.FollowDetailListAdapter.ViewHolders) viewHolderBase;
					viewHolder.collection_fram.setClickable(false);
					viewHolder.collection_name_linear.setClickable(false);
					viewHolder.collection_speed_relative.setClickable(false);
					viewHolder.collection_zan_linear.setClickable(false);
					viewHolder.collection_play_linear.setClickable(false);
					viewHolder.collection_download_linear.setClickable(false);
					
				}

				deleteBtnToClosed();
				
				return false;
			}
			break;
		case MotionEvent.ACTION_MOVE:
			moveX = Math.abs(x - downX);//X轴距离  
	        moveY = Math.abs(y - downY);//y轴距离  
			int dx = mLastX - x;
			int dy = mLastY - y;
				int scrollX = mItemLayout.getScrollX();
				MyLog.d(TAG, "Math.abs(dx) : " + Math.abs(dx) + " Math.abs(dy) : " + Math.abs(dy) + " moveX : " + moveX);
				if (Math.abs(dx) > Math.abs(dy)) {
					MyLog.d(TAG, "onInterceptTouchEvent scroll X : " + scrollX + " dx : " + dx + " mMaxLength : " + mMaxLength);
					isItemMoving = true;
				}
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			MyLog.d(TAG, "moveX : " + moveX + " moveY : " + moveY);
			if(moveX > 100 && moveY < 300){
				if (!isItemMoving && !isDragging && mListener != null) {
					mListener.onItemClick(mItemLayout, mPosition);
				}
				isItemMoving = false;

				float xVelocity = 0;
				float yVelocity = 0;

				if(mVelocityTracker != null){
					mVelocityTracker.computeCurrentVelocity(1000);// 计算手指滑动的速度
					xVelocity = mVelocityTracker.getXVelocity();// 水平方向速度（向左为负）
					yVelocity = mVelocityTracker.getYVelocity();// 垂直方向速度
				}

				int deltaX = 0;
				int upScrollX = mItemLayout.getScrollX();

				if (Math.abs(xVelocity) > 100
						&& Math.abs(xVelocity) > Math.abs(yVelocity)) {
					if (xVelocity <= -100) {// 左滑速度大于100，则删除按钮显示
							deltaX = mMaxLength - upScrollX;
							mDeleteBtnState = BTN_OPENING;
					} else if (xVelocity > 100) {// 右滑速度大于100，则删除按钮隐藏
						MyLog.d(TAG, "mDeleteBtnState 111");
							deltaX = -upScrollX;
							mDeleteBtnState = BTN_CLOSING;	
					}
				} else {
					if (upScrollX >= mMaxLength / 2) {// item的左滑动距离大于删除按钮宽度的一半，则则显示删除按钮
							deltaX = mMaxLength - upScrollX;
							mDeleteBtnState = BTN_OPENING;	
					} else if (upScrollX < mMaxLength / 2) {// 否则隐藏
						MyLog.d(TAG, "mDeleteBtnState 222");
							deltaX = -upScrollX;
							mDeleteBtnState = BTN_CLOSING;
					}
				}
				// item自动滑动到指定位置
				mScroller.startScroll(upScrollX, 0, deltaX, 0, 200);
				MyLog.d(TAG, "upScrollX : " + upScrollX + " deltaX : " + deltaX);
				isStartScroll = true;
				invalidate();
				if(mVelocityTracker != null)
				mVelocityTracker.clear();
				return true;
			}
		}
		mLastX = x;
		mLastY = y;
		MyLog.d(TAG, "onInterceptTouchEvent return last...");
		return false;
	}
	
    
	/**
	 * 让删除按钮缩回
	 */
	
	TimerTask task;
	Timer timer = new Timer(); 
		
	public void deleteBtnToClosed(){
		MyLog.d(TAG, "deleteBtnToClosed...");
		mScroller.startScroll(mItemLayout.getScrollX(), 0, -mMaxLength,
				0, 200);
		invalidate();
		delayRecoverState();
	}

	private void delayRecoverState() {
		if (timer != null){
		      if (task != null){
		    	  task.cancel();  //将原任务从队列中移除
		      }
		      task = new TimerTask() {  
		          @Override  
		          public void run() {  
		        	  Message message = new Message();  
		              message.what = 1;  
		              handler.sendMessage(message); 
		          }  
		      }; 
		      timer.schedule(task,200);
		}
	}
	
	
	Handler handler = new Handler() {  
        public void handleMessage(Message msg) {  
            if (msg.what == 1) {
            	
            	mDeleteBtnState = BTN_CLOSED;
            	MyLog.d(TAG, "mDeleteBtnState handler : " + mDeleteBtnState);
            	
            }  
            super.handleMessage(msg);  
        };  
    }; 
    
    /**
     * 当Delete或者Top确认后执行
     */
	public void startRecovery() {
		mItemLayout.scrollTo(0, 0);
		mDeleteBtnState = BTN_CLOSED;
	}
	
	/**
	 * 使区域不可点击
	 * @param x
	 * @param y
	 */
	public void recoveryClick(int x,int y){
		
		MyLog.d(TAG, "recoveryClick x : " + x + " y : " + y);
		
		View view = findChildViewUnder(x, y);
		if (view == null)return;
		
		
		ViewHolder viewHolderBase = getChildViewHolder(view);

		if (viewHolderBase instanceof CollectionListAdapter.ViewHolders) {
			CollectionListAdapter.ViewHolders viewHolder = (ViewHolders) viewHolderBase;
			viewHolder.collection_fram.setClickable(false);
			viewHolder.collection_name_linear.setClickable(false);
//			viewHolder.collection_default.setClickable(false);
			viewHolder.collection_zan_linear.setClickable(false);
			viewHolder.collection_play_linear.setClickable(false); 
			viewHolder.collection_download_linear.setClickable(false);

		}else if(viewHolderBase instanceof FollowDetailListAdapter.ViewHolders){
			FollowDetailListAdapter.ViewHolders viewHolder = (com.sensePlusVR.adapter.FollowDetailListAdapter.ViewHolders) viewHolderBase;
			viewHolder.collection_fram.setClickable(false);
			viewHolder.collection_name_linear.setClickable(false);
//			viewHolder.collection_default.setClickable(false);
			viewHolder.collection_zan_linear.setClickable(false);
			viewHolder.collection_play_linear.setClickable(false);
			viewHolder.collection_download_linear.setClickable(false);
			
		}
		
	}
	
	
	public int getmDeleteBtnState() {
		return mDeleteBtnState;
	}

	public void setmDeleteBtnState(int mDeleteBtnState) {
		this.mDeleteBtnState = mDeleteBtnState;
	}

	//(x,y)是否在view的区域内
	private boolean isTouchPointInView(View view, int x, int y) {
	        if (view == null) {
	            return false;
	        }
	        int[] location = new int[2];
	        view.getLocationOnScreen(location);
	        int left = location[0];
	        int top = location[1];
	        int right = left + view.getMeasuredWidth();
	        int bottom = top + view.getMeasuredHeight();
	        //view.isClickable() &&
	        if (y >= top && y <= bottom && x >= left
	                && x <= right) {
	            return true;
	        }
	        return false;
	    }

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			//MyLog.d(TAG, "computeScroll currX : " + mScroller.getCurrX() + " currY : " + mScroller.getCurrY());
			
			int currX = mScroller.getCurrX();
			if(currX < 0){
				currX = 0;
			} 
			if(currX > mMaxLength){
				currX = mMaxLength;
			}
			
			mItemLayout.scrollTo(currX, mScroller.getCurrY());
			invalidate();
			
		} else if (isStartScroll) {
			isStartScroll = false;
			
			MyLog.d(TAG, "computeScroll mDeleteBtnState : " + mDeleteBtnState);
			
			if (mDeleteBtnState == BTN_CLOSING) {
				mDeleteBtnState = BTN_CLOSED;
			}

			if (mDeleteBtnState == BTN_OPENING) {
				mDeleteBtnState = BTN_OPENED;
			}
		}
	}

	@Override
	protected void onAttachedToWindow() {
		mVelocityTracker = VelocityTracker.obtain();
		super.onAttachedToWindow();
	}

	@Override
	protected void onDetachedFromWindow() {
		if (mVelocityTracker != null) {
			mVelocityTracker.recycle();
			mVelocityTracker = null;
		}
		super.onDetachedFromWindow();
	}

	@Override
	public void onScrollStateChanged(int state) {
		super.onScrollStateChanged(state);
		isDragging = state == SCROLL_STATE_DRAGGING;
	}

	public void setOnItemClickListener(OnItemClickListener listener) {
		mListener = listener;
	}
}
